package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author 21829
 */
public class SimpleRedisLock implements ILock {

    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true);
    private String name;
    private StringRedisTemplate redisTemplate;
    private static final DefaultRedisScript<Long> DEFAULT_SCRIPT;
    static {
        DEFAULT_SCRIPT = new DefaultRedisScript<>();
        DEFAULT_SCRIPT.setResultType(Long.class);
        DEFAULT_SCRIPT.setLocation(new ClassPathResource("unLock.lua"));
    }

    public SimpleRedisLock(String name, StringRedisTemplate redisTemplate) {
        this.name = name;
        this.redisTemplate = redisTemplate;
    }
    //获取锁
    @Override
    public boolean tryLcok(Long timeOutSec) {
        //1.尝试获取锁 获取当前线程id作为value
        String id = ID_PREFIX + Thread.currentThread().getId();
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, id, timeOutSec, TimeUnit.SECONDS);
        return ifAbsent;
    }
    //释放锁
    @Override
    public void unLock() {
//        //1.获取当前唯一表示
//        String ThreadId = ID_PREFIX + Thread.currentThread().getId();
//        //2.获取redis中的唯一标识
//        String id = redisTemplate.opsForValue().get(KEY_PREFIX + name);
//        //3.相同则允许删除
//        if (ThreadId.equals(id)) {
//            redisTemplate.delete(KEY_PREFIX + name);
//        }
        redisTemplate.execute(DEFAULT_SCRIPT, Collections.singletonList(KEY_PREFIX + name), ID_PREFIX + Thread.currentThread().getId());
    }
}
